package mylab.utils.common;

import com.google.common.base.Joiner;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Getter;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;


/**
 * ShellUtils
 */
@Slf4j
@UtilityClass
public class ShellUtil {

    public final String COMMAND_SU = "su";
    public final String COMMAND_SH = "sh";
    public final String COMMAND_EXIT = "exit\n";
    public final String COMMAND_LINE_END = "\n";

    /**
     * 异步执行脚本，并返回进程ID
     *
     * @param command shell脚本
     * @return PID
     */
    public int asyncExecAndGetPid(String command) {
        int pid = -1;

        try {
            Runtime.getRuntime().exec(new String[]{"bash", "-c", command});
            return getPid(command);
        } catch (Exception e) {
            logError(e);
        }

        return pid;
    }

    public int getPid(){
        return getPid("echo $$");
    }

    /**
     * 获取shell指令进程ID
     *
     * @param command shell指令,失败时返回-1
     * @return PID
     */
    public int getPid(String command) {
        int pid = -1;

        try {
            // 获取PID
            String cmdPs = StringUtil.format("ps aux | grep '{}' | grep -v grep | awk '{print $2}'", command);
            Process pidProcess = Runtime.getRuntime().exec(new String[]{"bash", "-c", cmdPs});
            BufferedReader pidReader = new BufferedReader(new InputStreamReader(pidProcess.getInputStream()));
            String pidLine = pidReader.readLine();
            if (pidLine != null) {
                pid = Integer.parseInt(pidLine.trim());
                log.info("PID: " + pid);
                return pid;
            } else {
                log.info("PID not found.");
            }
        } catch (Exception e) {
            logError(e);
        }

        return pid;
    }

    /**
     * 强制杀死进程
     *
     * @param pid pid
     */
    public void kill(int pid) {
        execCommand(StringUtil.format("kill -9 {}", pid), false);
    }


    /**
     * 生成globbing(shell通配符)
     */
    public String genGlobbing(List<String> items) {
        if (items == null || items.isEmpty()) {
            return "*";
        } else {
            return "{" + Joiner.on(",").skipNulls().join(items) + "}";
        }
    }

    /**
     * check whether has root permission
     */
    public boolean checkRootPermission() {
        return execCommand("echo root", true, false).result == 0;
    }

    /**
     * execute shell command, default return result msg
     *
     * @param command command
     * @param isRoot  whether need to run with root
     * @see ShellUtil#execCommand(String[], boolean, boolean)
     */
    public CommandResult execCommand(String command, boolean isRoot) {
        return execCommand(new String[]{command}, isRoot, true);
    }

    /**
     * execute shell commands, default return result msg
     *
     * @param commands command list
     * @param isRoot   whether need to run with root
     * @see ShellUtil#execCommand(String[], boolean, boolean)
     */
    public CommandResult execCommand(List<String> commands, boolean isRoot) {
        return execCommand(commands == null ? null : commands.toArray(new String[]{}), isRoot, true);
    }

    /**
     * execute shell commands, default return result msg
     *
     * @param commands command array
     * @param isRoot   whether need to run with root
     * @see ShellUtil#execCommand(String[], boolean, boolean)
     */
    public CommandResult execCommand(String[] commands, boolean isRoot) {
        return execCommand(commands, isRoot, true);
    }

    /**
     * execute shell command
     *
     * @param command         command
     * @param isRoot          whether need to run with root
     * @param isNeedResultMsg whether need result msg
     * @see ShellUtil#execCommand(String[], boolean, boolean)
     */
    public CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
        return execCommand(new String[]{command}, isRoot, isNeedResultMsg);
    }

    /**
     * execute shell commands
     *
     * @param commands        command list
     * @param isRoot          whether need to run with root
     * @param isNeedResultMsg whether need result msg
     * @see ShellUtil#execCommand(String[], boolean, boolean)
     */
    public CommandResult execCommand(List<String> commands, boolean isRoot, boolean isNeedResultMsg) {
        return execCommand(commands == null ? null : commands.toArray(new String[]{}), isRoot, isNeedResultMsg);
    }

    /**
     * execute shell commands
     *
     * @param commands        command array
     * @param isRoot          whether need to run with root
     * @param isNeedResultMsg whether need result msg
     * @return <ul>
     * <li>if isNeedResultMsg is false, {@link CommandResult#successMsg} is null and
     * {@link CommandResult#errorMsg} is null.</li>
     * <li>if {@link CommandResult#result} is -1, there maybe some excepiton.</li>
     * </ul>
     */
    public CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, null);
        }

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;

        DataOutputStream os = null;
        try {
            ProcessBuilder builder = new ProcessBuilder(isRoot ? COMMAND_SU : COMMAND_SH);
            process = builder.start();
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command == null) {
                    continue;
                }

                // donnot use os.writeBytes(commmand), avoid chinese charset error
                os.write(command.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
            }
            os.writeBytes(COMMAND_EXIT);
            os.flush();

            result = process.waitFor();
            // get command result
            if (isNeedResultMsg) {
                successMsg = new StringBuilder();
                errorMsg = new StringBuilder();
                successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s);
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s);
                }
            }
        } catch (Exception e) {
            logError(e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                logError(e);
            }

            if (process != null) {
                process.destroy();
            }
        }

        return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
                : errorMsg.toString());
    }

    private void logError(Exception e) {
        log.error(e.getMessage(), e);
    }

    /**
     * result of command
     * <ul>
     * <li>{@link CommandResult#result} means result of command, 0 means normal, else means error, same to excute in
     * linux shell</li>
     * <li>{@link CommandResult#successMsg} means success message of command result</li>
     * <li>{@link CommandResult#errorMsg} means error message of command result</li>
     * </ul>
     *
     * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-5-16
     */
    @Getter
    public class CommandResult {

        /**
         * result of command
         **/
        int result;
        /**
         * success message of command result
         **/
        String successMsg;
        /**
         * error message of command result
         **/
        String errorMsg;

        public CommandResult(int result) {
            this.result = result;
        }

        public CommandResult(int result, String successMsg, String errorMsg) {
            this.result = result;
            this.successMsg = successMsg;
            this.errorMsg = errorMsg;
        }
    }


    public static void main(String[] args) {

        //注意： shell指令中不要有多余的空格
        String command = "ffmpeg -f avfoundation -framerate 30 -i 0:0 -vcodec libx264 -an -f flv rtmp://office.lianyi-inc.com/live/livestream";
        int pid = asyncExecAndGetPid(command);
        log.info("pid=" + pid);

        for (int i = 1; i <= 20; i++) {
            ThreadUtil.sleep(1000);
            log.info(StringUtil.format("sleep {} 秒", i));
        }
        log.info("sleep over");
        ShellUtil.kill(pid);

    }
}
